% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/calibrate_2way.R
\name{calib_twoway}
\alias{calib_twoway}
\title{Find two-way correction for cell estimates}
\source{
Kuriwaki, S., Ansolabehere, S., Dagonel, A., & Yamauchi, S. (2021).
The Geography of Racially Polarized Voting: Calibrating Surveys at the
District Level. \url{https://doi.org/10.31219/osf.io/mk9e6}
}
\usage{
calib_twoway(
  data,
  var_area,
  var_group,
  tgt_area,
  tgt_group,
  n_area,
  n_group,
  n_total,
  delta_init = NULL,
  use_grad = TRUE
)
}
\arguments{
\item{data}{Estimates stored in the long format. Must be coercible to a non-tibble dataframe.
The column should be named \code{est} and the sample size should be called \code{n}.}

\item{var_area}{Variable name (char) for area in \code{data}.}

\item{var_group}{Variable name (char) for group in \code{data}.}

\item{tgt_area}{Vector of true values for area. Must be named so that the names indicate
the area that corresponds to the number.}

\item{tgt_group}{Vector of true values for group. Must be named so that the names indicate
the group that corresponds to the number.}

\item{n_area}{Vector consists of population sizes in each area.}

\item{n_group}{Vector consists of population sizes for each group.}

\item{n_total}{Scalar of total number of population.}

\item{delta_init}{Initial values of delta.}

\item{use_grad}{Whether to use the gradient function to speed up the optimization.
Default is \code{TRUE}.}
}
\value{
Data frame with new columns \code{"est_corrected"} and \code{"delta"}
}
\description{
Find two-way correction for cell estimates
}
\examples{
\dontrun{
library(dplyr)
library(tibble)
library(tictoc)

# MRP estimates
drw_GA_educ <- poststrat_draws(fit_GA, poststrat_tgt = acs_GA, area_var = c("cd", "educ"))
acs_GA_educ <- acs_GA \%>\% count(cd, educ, wt = count, name = "N")

# for a particular draw
i <- 1

# Data at cell level
draw_i <- drw_GA_educ \%>\%
  filter(iter == i) \%>\%
  left_join(acs_GA_educ, by = c("cd", "educ")) \%>\%
  rename(est = p_mrp, n = N)


# ys
elec_tgt <- deframe(select(elec_GA, cd, clinton_vote_2pty))
educ_tgt <- c(`HS or Less` = 0.40, `Some College` = 0.45, `4-Year` = 0.50, `Post-Grad` = 0.60)

# Ns
area_N <- deframe(count(acs_GA_educ, cd, wt = N))
educ_N <- deframe(count(acs_GA_educ, educ, wt = N))
totalN <- deframe(count(acs_GA_educ, wt = N))

# Run
set.seed(02138)
out <- calib_twoway(
  data = draw_i,
  var_area = "cd",
  var_group = "educ",
  tgt_area  = elec_tgt,
  tgt_group = educ_tgt,
  n_area = area_N,
  n_group = educ_N,
  n_total = totalN,
  use_grad = TRUE
)
}

}
\seealso{
calib_oneway
}
